package home.project;

import flash.display.Graphics;
import home.project.misc.Camera;
import home.project.misc.Quadtree;
import home.project.misc.Rect;
import home.project.misc.Spritesheet;
import home.project.misc.Tilemap;
import openfl.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.Lib;
import openfl.Assets;
import home.project.misc.Tilemap;
import openfl.geom.Point;

/**
 * ...
 * @author an.vuongngocduy
 */

class Main extends Sprite 
{
	var inited:Bool;
	var lastTime:Int;
	var map:Tilemap;
	var spr:Spritesheet;
	var quad:Quadtree;
	var cam:Camera;
	/* ENTRY POINT */
	
	function resize(e) 
	{
		if (!inited) init();
		// else (resize or orientation change)
	}
	
	function init() 
	{
		if (inited) return;
		inited = true;
			
		// (your code here)
		
		// Stage:
		// stage.stageWidth x stage.stageHeight @ stage.dpiScale
		
		// Assets:
		// nme.Assets.getBitmapData("img/assetname.jpg");
		
		map = Tilemap.loadTMX("img/sewers.tmx");
		map.loadCollisions(Assets.getText("img/collisionmap.txt"));

		
		spr = Spritesheet.load("img/tuxsprite.xml");
		spr.position = new Point(5, 0);
		spr.isCollidable = true;
		spr.velocity.y = 1.0;
		spr.acceleration.y = 5.0;
		
		quad = new Quadtree(0, 0, map.tileWidth * map.widthInTiles , map.tileHeight * map.heightInTiles);
		
		cam = new Camera(400, 150);
		cam.follow(spr);
	}

	/* SETUP */

	public function new() 
	{
		super();	
		addEventListener(Event.ADDED_TO_STAGE, added);
		addEventListener(Event.ENTER_FRAME, enterFrame);
	}

	function added(e) 
	{
		removeEventListener(Event.ADDED_TO_STAGE, added);
		stage.addEventListener(Event.RESIZE, resize);
		
		stage.addEventListener(KeyboardEvent.KEY_DOWN, Globals.keyboard.onKeyDown);
		stage.addEventListener(KeyboardEvent.KEY_UP, Globals.keyboard.onKeyUp);
		
		#if ios
		haxe.Timer.delay(init, 100); // iOS 6
		#else
		init();
		#end
		Globals.sStage = this.stage;
		Globals.sGraphics = this.graphics;
	}
	
	function enterFrame(e)
	{
		Globals.sElapsedTime = Lib.getTimer() - lastTime;
		lastTime = Lib.getTimer();
		
		graphics.clear();
		
		map.draw(graphics);
		spr.draw(graphics);
		quad.draw(graphics);
		
		quad.clear();
		quad.push(map);
		quad.push(spr);
		quad.traverse();
		cam.draw(graphics);
		
		spr.update(0);
		cam.update(0);
	}
	
	public static function main() 
	{
		// static entry point
		Lib.current.stage.align = flash.display.StageAlign.TOP_LEFT;
		Lib.current.stage.scaleMode = flash.display.StageScaleMode.NO_SCALE;
		Lib.current.addChild(new Main());
	}
}
